package com.cloudfun.campusshare.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cloudfun.campusshare.common.model.dto.AuditDTO;
import com.cloudfun.campusshare.common.model.vo.AuditVO;
import com.cloudfun.campusshare.common.security.AuthenticationHolder;
import com.cloudfun.campusshare.entity.AuditEntity;
import com.cloudfun.campusshare.repo.AuditEntityRepo;
import com.cloudfun.campusshare.repo.UserEntityRepo;
import com.cloudfun.campusshare.service.AuditService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Huqin on 2019/12/30
 */
@Slf4j
@Service
public class AuditServiceImpl implements AuditService {

    @Autowired
    private AuditEntityRepo auditEntityRepo;

    @Autowired
    private UserEntityRepo userEntityRepo;

    @Override
    public AuditEntity create(AuditDTO auditDT) {
        AuditEntity auditEntity = AuditEntity.builder()
                .applicationId(auditDT.getApplicationId())
                .result(auditDT.getAuditResult())
                .remark(auditDT.getRemark())
                .operator(userEntityRepo.findById(AuthenticationHolder.getUserId()).get())
                .build();
        auditEntityRepo.save(auditEntity);
        return auditEntity;
    }

    @Override
    public List<AuditVO> getByApplicationId(String applicationId) {
        List<AuditEntity> auditEntities = auditEntityRepo.findAllByApplicationIdOrderByCreateTime(applicationId);
        List<AuditVO> auditVOList = auditEntities.stream()
                .map(auditEntity -> {
                    AuditVO auditVO = new AuditVO();
                    BeanUtil.copyProperties(auditEntity, auditVO);
                    auditVO.setOperatorId(auditEntity.getOperator().getId());
                    auditVO.setOperatorName(auditEntity.getOperator().getUsername());
                    return auditVO;
                }).collect(Collectors.toList());
        return auditVOList;
    }

    @Override
    @Transactional
    public void deleteByApplicationId(String applicationId) {
        List<AuditEntity> auditEntities = auditEntityRepo.findAllByApplicationId(applicationId);
        auditEntityRepo.deleteAll(auditEntities);
    }

    @Override
    public AuditEntity getLatestByApplicationId(String applicationId) {
        return auditEntityRepo.findFirstByApplicationIdOrderByCreateTimeDesc(applicationId);
    }
}
